﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

/// <summary>
/// Summary description for DataBase
/// </summary>
public static class DataBase
{
    //public static String ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\ProjectOnline\WebBanOto\App_Data\Oto.mdf;Integrated Security=True;User Instance=True";    

    public static SqlConnection GetConnection()
    {
        //return new SqlConnection(ConnectionString);
        return new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    }

    public static DataTable Fill(DataTable table, String sql, params Object[] parameters)
    {
        SqlCommand command = DataBase.CreateCommand(sql, parameters);
        new SqlDataAdapter(command).Fill(table);
        command.Connection.Close();
        return table;
    }

    public static DataTable GetDataTable(String sql, params Object[] parameters)
    {
        return DataBase.Fill(new DataTable(), sql, parameters);
    }

    public static int ExecuteNonQuery(String sql, params Object[] parameters)
    {
        SqlCommand command = DataBase.CreateCommand(sql, parameters);
        command.Connection.Open();
        int rows = command.ExecuteNonQuery();
        command.Connection.Close();
        return rows;
    }

    public static object ExecuteScalar(String sql, params Object[] parameters)
    {
        SqlCommand command = DataBase.CreateCommand(sql, parameters);
        command.Connection.Open();
        object value = command.ExecuteScalar();
        command.Connection.Close();
        return value;
    }

    private static SqlCommand CreateCommand(String sql, params Object[] parameters)
    {
        SqlCommand command = new SqlCommand(sql, DataBase.GetConnection());
        for (int i = 0; i < parameters.Length; i += 2)
        {
            command.Parameters.AddWithValue(parameters[i].ToString(), parameters[i + 1]);
        }
        return command;
    }
}
